/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package securityfacade;

import java.rmi.RemoteException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import rmiinterfaces.SecurityInterface;

/**
 * Classes that performs authentication of user based on the username and password provided
 * @author Group 10
 */
public class AuthenticationImplementation implements AuthenticationInterface {
    
    /***
     * Method that accepts a user name and password, and returns whether authentication was succesfull
     * @param login
     * @param psw
     * @return AuthReturn enumeration
     * @throws RemoteException 
     */
    public SecurityInterface.AuthReturn authenticate(String login, String psw) throws RemoteException {
        boolean connectError = false;
        Connection DBConn = null;
        try {
            //load JDBC driver class for MySQL
            Class.forName("com.mysql.jdbc.Driver");


            //define the data source
            String sourceURL = "jdbc:mysql://127.0.0.1:3306/authentication";

            DBConn = DriverManager.getConnection(sourceURL, "remote", "remote_pass");

        } catch (Exception e) {
            
            System.err.println("\nProblem connecting to database:: "+e.toString());
            connectError = true;
        } // end try-catch



        //If there is not connection error, then we form the SQL statement
        //and then execute it.

        if (!connectError) {
            try {
                //created prepared query statement
                String sql = "select * from Users where (username = ? and password = ?)";

                PreparedStatement preparedStmt = DBConn.prepareStatement(sql);
                preparedStmt.setString(1, login);
                preparedStmt.setString(2, psw);
                
                //executing query and checking whether valid authentication
                ResultSet results = preparedStmt.executeQuery();
                if (results.next()) {
                    System.out.println("TRUE");
                    return SecurityInterface.AuthReturn.TRUE;
                } else {
                    System.out.println("FALSE");
                    return SecurityInterface.AuthReturn.FALSE;
                }
                
            } catch (Exception e) {
                //Db exceptionException 
                System.err.println("Authentication db error");
            } finally{
                //close connection
                try {
                    DBConn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(AuthenticationImplementation.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //return authentication failed
        return SecurityInterface.AuthReturn.FALSE;
    }
}
